package snippet;

import java.io.IOException;

import javax.bluetooth.L2CAPConnection;
import javax.bluetooth.L2CAPConnectionNotifier;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.UUID;
import javax.microedition.io.Connector;

public class Server
    implements
        Runnable
{

    private UUID uuid;
    private String url;
    private L2CAPConnectionNotifier lcnotifier;
    private L2CAPConnection lc;
    private Envelope envelope;
    private Status status;

    public Server(
        String urlString,
        Envelope envelope,
        Status status )
    {
        uuid = new UUID( urlString, true );
        url = "btl2cap://localhost:" + uuid.toString() + ";ReceiveMTU=512;TransmitMTU=512";
        this.envelope = envelope;
        this.status = status;
    }

    @Override
    public void run()
    {
        RemoteDevice remoteDevice;
        boolean ligado;
        try {
            lcnotifier = (L2CAPConnectionNotifier) Connector.open( url );
            while( true ) {
                ligado = status.getStatus();
                if( ! ligado )
                    break;
                lc = lcnotifier.acceptAndOpen();
                remoteDevice = RemoteDevice.getRemoteDevice( lc );
                envelope.set( remoteDevice );
            }
        } catch( IOException e ) {
            System.out.println( "Server: tentativa de abrir conexão mal sucedida" );
        }
    }
}